from langchain_mcp_adapters.client import MultiServerMCPClient
import asyncio
from core.config import settings

async def get_webService_client():
    DASHSCOPE_API_KEY = settings.LLM_API_KEY_ALIBABA
    mcp_config: dict = {
        "mcpServers": {
            "transport": "sse",
            "url": "https://dashscope.aliyuncs.com/api/v1/mcps/WebSearch/sse",
            "headers": {
                "Authorization": DASHSCOPE_API_KEY

            }
        }
    }
    # 初始化客户端
    web_service = MultiServerMCPClient(mcp_config)
    return web_service


# 异步工具调用函数
async def web_service_async(query: str, date: str) -> str:
    try:
        client = await get_webService_client()
        result = await client.arun(
            query=query,
            date=date,

        )
        return result if result else "未获取到搜索结果"
    except Exception as e:
        # 捕获异常
        error_msg = f"WebSearch调用失败：{str(e)}"
        # 打印详细日志便于排查
        print(error_msg, exc_info=True)
        # 返回错误信息
        return f"搜索失败：{error_msg}"